﻿using Prism.Events;
using Prism.Ioc;
using System.Windows;
using System.Windows.Controls;
using Xcj.Mes.WholeLine.ZH.HG.Shell.Events;

namespace Xcj.Mes.WholeLine.ZH.HG.Shell.Views.Main
{
    /// <summary>
    /// WorkRegionView.xaml 的交互逻辑
    /// </summary>
    public partial class WorkRegionView : UserControl
    {
        protected IEventAggregator _eventAggregator { get; private set; }
        
        public WorkRegionView()
        {
            InitializeComponent();

            // 订阅事件
            _eventAggregator = ((Prism.PrismApplicationBase)System.Windows.Application.Current).Container.Resolve<IEventAggregator>();

            this.Loaded += ((o, e) =>
            {
                try { _eventAggregator?.GetEvent<ToolBarSelectedEvent>()?.Subscribe(OnToolBarSelected); } catch { }
            });

            this.Unloaded += ((o, e) =>
            {
                try { _eventAggregator?.GetEvent<ToolBarSelectedEvent>()?.Unsubscribe(CloseWindow); } catch { }
            });
        }
        
        private void CloseWindow(string header)
        {
            try
            {
                //// 如果是 Window
                //if (this is System.Windows.Window window)
                //    window.Close();
                //// 如果是 UserControl，关闭其所属 Window
                //else
                    Window.GetWindow(this)?.Close();
            }
            catch { }
        }

        private void OnToolBarSelected(string header)
        {
            if(header?.Contains("用户登录") ?? false)
            {
                LoginView loginView = new LoginView();
                loginView.ShowDialog();
            }
            else
            {
                foreach (var item in ToolBarTabCtrl.Items)
                {
                    string text = item.ToString();
                    if (text?.Contains(header) ?? false)
                    {
                        ToolBarTabCtrl.SelectedItem = item;
                        break;
                    }
                }
            }
        }
    }
}
